package com.note.app.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RabbitMQ配置类
 */
@Configuration
public class RabbitMQConfig {

    /**
     * 日志交换机
     */
    public static final String LOG_EXCHANGE = "log.exchange";
    
    /**
     * 请求日志队列
     */
    public static final String REQUEST_LOG_QUEUE = "request.log.queue";
    
    /**
     * 请求日志路由键
     */
    public static final String REQUEST_LOG_ROUTING_KEY = "request.log";
    
    /**
     * 配置日志交换机
     */
    @Bean
    public DirectExchange logExchange() {
        return new DirectExchange(LOG_EXCHANGE);
    }
    
    /**
     * 配置请求日志队列
     */
    @Bean
    public Queue requestLogQueue() {
        // 队列持久化
        return new Queue(REQUEST_LOG_QUEUE, true);
    }
    
    /**
     * 绑定请求日志队列到日志交换机
     */
    @Bean
    public Binding requestLogBinding(Queue requestLogQueue, DirectExchange logExchange) {
        return BindingBuilder.bind(requestLogQueue)
                .to(logExchange)
                .with(REQUEST_LOG_ROUTING_KEY);
    }
    
    /**
     * 配置消息转换器
     */
    /*@Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }*/
    
    /**
     * 配置RabbitTemplate
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, MessageConverter jsonMessageConverter) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(jsonMessageConverter);
        return rabbitTemplate;
    }

    @Bean
    public Jackson2JsonMessageConverter jsonMessageConverter() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        // 配置日期时间格式
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        return new Jackson2JsonMessageConverter(objectMapper);
    }
} 